<script setup>
import { ref } from 'vue'
const dialogVisible = ref(false)
import {
  userlandReinfoAddService,
  userlandReinfoUpService
} from '@/api/user/landresource'

const formModel = ref({
  id: '',
  name: '',
  address: '',
  parcelcount: '',
  userid: '',
  tar: ''
})
const rules = {
  name: [
    { required: true, message: '请输入土地名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  parcelcount: [
    { required: true, message: '请输入土地资源所拥有的块数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const reg = /^[1-9]\d*$/ // 正整数的正则表达式 开头1-9，后边\d0各或者多个
        if (!reg.test(value)) {
          callback(new Error('请输入有效块数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const form = ref()
const showButton = ref()
const countryDisabled = ref(false)
const proviceDisabled = ref(false)
const cityDisabled = ref(false)
const detailAdressDisabled = ref(false)
const addressDetail = ref({})
const baiduPrivice = ref()
const baiduCity = ref()
const baiduCityBelong = ref()
const addresscontainer = ref({
  initprovice: '',
  changedprovice: '',
  initcity: '',
  changedcity: '',
  changedcountry: '',
  initcountry: ''
})

import { useUserStore } from '@/stores'
const emit = defineEmits(['success'])
const sureQuire = async () => {
  await form.value.validate()
  formModel.value.tar = '1'

  const isEdit = formModel.value.id
  if (isEdit) {
    if (formModel.value.address) {
      userlandReinfoUpService(formModel.value)
        .then((response) => {
          if (response.data.status == '200') {
            dialogVisible.value = false
            emit('success')
            ElMessage.success(response.data.message)
          } else {
            dialogVisible.value = false
            ElMessage.error(response.data.message)
          }
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    } else {
      ElMessage.error('修改失败， 请选择完整的地址')
    }
    //ElMessage.success(formModel.value.address)
  } else {
    //添加操作
    formModel.value.userid = `${useUserStore().user.id}`
    if (formModel.value.address) {
      userlandReinfoAddService(formModel.value)
        .then((response) => {
          if (response.data.status == '200') {
            dialogVisible.value = false
            emit('success')
            ElMessage.success(response.data.message)
          } else {
            dialogVisible.value = false
            ElMessage.error(response.data.message)
          }
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    } else {
      ElMessage.error('修改失败， 请选择完整的地址')
    }
  }
  dialogVisible.value = false
  proviceDisabled.value = false
  emit('success')
  addresscontainer.value.initprovice = ''
  addresscontainer.value.changedprovice = ''
  addresscontainer.value.initcity = ''
  addresscontainer.value.changedcity = ''
  addresscontainer.value.changedcountry = ''
  addresscontainer.value.initcountry = ''
}
const NoQuire = () => {
  form.value.resetFields()
  dialogVisible.value = false
  addresscontainer.value.initprovice = ''
  addresscontainer.value.changedprovice = ''
  addresscontainer.value.initcity = ''
  addresscontainer.value.changedcity = ''
  addresscontainer.value.changedcountry = ''
  addresscontainer.value.initcountry = ''
  proviceDisabled.value = false
}
const handleClose = () => {
  form.value.resetFields()
  dialogVisible.value = false
  addresscontainer.value.initprovice = ''
  addresscontainer.value.changedprovice = ''
  addresscontainer.value.initcity = ''
  addresscontainer.value.changedcity = ''
  addresscontainer.value.changedcountry = ''
  addresscontainer.value.initcountry = ''
  proviceDisabled.value = false
}

const handleClearValidate = () => {}
const clearAddress = () => {
  formModel.value.address = ''
  addresscontainer.value.initprovice = ''
  addresscontainer.value.changedprovice = ''
  addresscontainer.value.initcity = ''
  addresscontainer.value.changedcity = ''
  addresscontainer.value.changedcountry = ''
  addresscontainer.value.initcountry = ''
  proviceDisabled.value = false
  cityDisabled.value = true
  countryDisabled.value = true
  detailAdressDisabled.value = true
  addressDetail.value[3] = ''
}
import axios from 'axios'
const open = (row) => {
  dialogVisible.value = true
  formModel.value = { ...row } //添加的话，重置表单内容

  if (formModel.value.id) {
    showButton.value = true
    countryDisabled.value = true
    cityDisabled.value = true
    detailAdressDisabled.value = true
    addressDetail.value = formModel.value.address.split(' ')
    axios
      .get(
        'api_region_search/v1/?keyword=中国&sub_admin=3&ak=nqSAq8S0isAO5oeDnN6S3amqh9SB2aMP'
      )
      .then(async (response) => {
        baiduPrivice.value = response.data.districts[0].districts

        for (let i = 0; i < baiduPrivice.value.length; i++) {
          if (baiduPrivice.value[i].name === addressDetail.value[0]) {
            addresscontainer.value.initprovice = i
            addresscontainer.value.changedprovice = i
          }
        }
        //拿到省下级的index
        baiduCity.value =
          baiduPrivice.value[addresscontainer.value.initprovice].districts
        for (let i = 0; i < baiduCity.value.length; i++) {
          if (baiduCity.value[i].name === addressDetail.value[1]) {
            addresscontainer.value.initcity = i
            addresscontainer.value.changedcity = i
          }
        } //拿到市下一级
        baiduCityBelong.value =
          baiduCity.value[addresscontainer.value.changedcity].districts
        for (let i = 0; i < baiduCityBelong.value.length; i++) {
          if (baiduCityBelong.value[i].name === addressDetail.value[2]) {
            addresscontainer.value.changedcountry = i
            addresscontainer.value.initcountry = i
          }
        }
      })
      .catch((error) => {
        console.error(error)
      })
  } else {
    //添加操作的
    addressDetail.value = ['', '', '']
    showButton.value = true
    axios
      .get(
        'api_region_search/v1/?keyword=中国&sub_admin=3&ak=nqSAq8S0isAO5oeDnN6S3amqh9SB2aMP'
      )
      .then(async (response) => {
        baiduPrivice.value = response.data.districts[0].districts
        //console.log('添加')
      })
      .catch((error) => {
        console.error(error)
      })
    countryDisabled.value = true
    cityDisabled.value = true
    detailAdressDisabled.value = true
  }
}
const handleSelectProviceChange = () => {
  //第一个省级填写直接编写完整地址
  if (formModel.value.id) {
    // formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} `
    baiduCity.value =
      baiduPrivice.value[addresscontainer.value.changedprovice].districts
    // formModel.value.address = `${formModel.value.address}${baiduCity.value[0].name} `
    // baiduCityBelong.value =
    //   baiduCity.value[addresscontainer.value.changedcity].districts
    // formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[0].name} `
    // formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
    proviceDisabled.value = true
    cityDisabled.value = false
    addresscontainer.value.changedcity = ''
    addresscontainer.value.changedcountry = ''
    formModel.value.address = ''
  } else {
    //formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} `
    baiduCity.value =
      baiduPrivice.value[addresscontainer.value.changedprovice].districts
    proviceDisabled.value = true
    cityDisabled.value = false
  }
}

const handleSelectCityChange = () => {
  if (formModel.value.id) {
    // formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} ` //第一次值
    // baiduCity.value =
    //   baiduPrivice.value[addresscontainer.value.changedprovice].districts //数据拔一层

    // formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
    baiduCityBelong.value =
      baiduCity.value[addresscontainer.value.changedcity].districts //传值下去
    cityDisabled.value = true
    countryDisabled.value = false

    // formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[0].name} `
    // formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
    //console.log(formModel.value.address)
  } else {
    ///formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
    baiduCityBelong.value =
      baiduCity.value[addresscontainer.value.changedcity].districts //传值下去
    cityDisabled.value = true
    countryDisabled.value = false
  }
}
const handleSelectCityBelongChange = () => {
  if (formModel.value.id) {
    formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} ` //第一个
    baiduCity.value =
      baiduPrivice.value[addresscontainer.value.changedprovice].districts //拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
    baiduCityBelong.value =
      baiduCity.value[addresscontainer.value.changedcity].districts //在拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} `
    formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
    countryDisabled.value = true
    detailAdressDisabled.value = false
  } else {
    //formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} ` //变动的值加上去
    formModel.value.address = `${`${`${baiduPrivice.value[addresscontainer.value.changedprovice].name} `}${baiduCity.value[addresscontainer.value.changedcity].name} `}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} ` //变动的值加上去

    detailAdressDisabled.value = false
    countryDisabled.value = true
  }
  //console.log(formModel.value.address)
}
const handleDetailAdressInput = () => {
  if (formModel.value.id) {
    formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} ` //第一个
    baiduCity.value =
      baiduPrivice.value[addresscontainer.value.changedprovice].districts //拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
    baiduCityBelong.value =
      baiduCity.value[addresscontainer.value.changedcity].districts //在拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} `
    formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
    //console.log(formModel.value.address)
    detailAdressDisabled.value = true
  } else {
    //formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
    formModel.value.address = `${`${`${`${baiduPrivice.value[addresscontainer.value.changedprovice].name} `}${baiduCity.value[addresscontainer.value.changedcity].name} `}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} `}${addressDetail.value[3]}`

    detailAdressDisabled.value = true
    console.log(formModel.value.address)
  }
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '修改' : '添加'"
    width="550"
    :before-close="handleClose"
  >
    <el-form
      class="el-form"
      :rules="rules"
      ref="form"
      :model="formModel"
      :before-close="handleClearValidate"
    >
      <el-form-item prop="name" label="土地名称" required="true">
        <el-input
          v-model="formModel.name"
          :prefix-icon="User"
          placeholder="请输入土地名称"
          style="width: 150px"
        ></el-input>
      </el-form-item>

      <el-form-item prop="parcelcount" label="地块数" required="true">
        <el-input
          v-model="formModel.parcelcount"
          type="number"
          :prefix-icon="Iphone"
          placeholder="请输入地块数"
          min="1"
        ></el-input>
      </el-form-item>
      <el-form-item label=" 地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址" required="true">
        <el-select
          placeholder="省份"
          v-model="addresscontainer.changedprovice"
          @change="handleSelectProviceChange"
          :disabled="proviceDisabled"
        >
          <el-option
            v-for="(item, index) in baiduPrivice"
            :key="index"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
        <el-select
          placeholder="市/区"
          v-model="addresscontainer.changedcity"
          @change="handleSelectCityChange"
          :disabled="cityDisabled"
        >
          <el-option
            v-for="(item, index) in baiduCity"
            :key="index"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
        <el-select
          placeholder="乡镇区县"
          v-model="addresscontainer.changedcountry"
          @change="handleSelectCityBelongChange"
          :disabled="countryDisabled"
        >
          <el-option
            v-for="(item, index) in baiduCityBelong"
            :key="index"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input
          placeholder="请输入详细地址"
          v-model="addressDetail[3]"
          @change="handleDetailAdressInput"
          :disabled="detailAdressDisabled"
          :style="{ width: '450px' }"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          style="margin-left: 395px; margin-top: 10px"
          plain
          @click="clearAddress"
          v-if="showButton"
          >清空地址信息</el-button
        >
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="NoQuire">取消</el-button>
        <el-button type="primary" @click="sureQuire"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style>
.el-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}
</style>
